package org.tnaggs.project.repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.tnaggs.project.model.League;

public class LeagueRepository implements GenericRepository<League> {
	
	
	private JdbcTemplate template;
	
	public LeagueRepository(JdbcTemplate template) {
		this.setTemplate(template);
	}

	public JdbcTemplate getTemplate() {
		return template;
	}

	public void setTemplate(JdbcTemplate template) {
		this.template = template;
	}

	@Override
	public League findByID(int id) {
		return (League)template.queryForObject("select * from League where League_ID = " + id, new LeagueRowMapper());
	}
	
	@Override
	public List<League> findAll() {
		return (List<League>)template.query("select * from League", new LeagueRowMapper());
	}
	
	class LeagueRowMapper implements RowMapper<League> {

		@Override
		public League mapRow(ResultSet rs, int arg1) throws SQLException {
		
				League results = new League();
				results.setLeagueId(rs.getInt("League_ID"));
				results.setLeagueName(rs.getString("Name"));
				results.setSeason(rs.getString("Season"));
				results.setYear(rs.getInt("Year"));
				results.setAdmin(rs.getInt("Admin"));
				return results;
		}

		
		
	}


	@Override
	public boolean insert(League newVal) {
		int numResults = template.update("insert into League (`Name`,`Season`,`Year`,`Admin`) values('" 
				+ newVal.getLeagueName() + "','" + newVal.getSeason() + "'," + newVal.getYear() 
				+ "," + newVal.getAdmin() + ")");
		return numResults == 1;
	}

	@Override
	public boolean delete(int id) {
		int numResults =  template.update("delete from League where League_ID = " + id);
		return numResults == 1;
	}

	@Override
	public boolean purge() {
      int numResults = template.queryForInt("select count(*) from League;");
      int delResults = template.update("delete from League;");
      return numResults == delResults;
	}

	public League findByName(String leagueName) {
		return (League)template.queryForObject("select * from League where Name = '" + leagueName + "'", new LeagueRowMapper());
	}
}
